"use strict";

const path = require("node:path");

const { rspack } = require("@rspack/core");
const { RspackDevServer } = require("@rspack/dev-server");
const connect = require("connect");
const express = require("express");

const app = express();

const config = require("./rspack.config.cjs");

const compiler = rspack(config);
const middleware = rspack.experiments.lazyCompilationMiddleware(compiler);
const server = new RspackDevServer(
  {
    setupMiddlewares: (other) => [middleware, ...other],
    devMiddleware: {
      index: true,
      mimeTypes: { phtml: "text/html" },
      serverSideRender: true,
      stats: "detailed",
    },
  },
  compiler,
);

app.use(() => server);
app.use(connect());
app.use(
  express.static(path.join(__dirname, "dist"), {
    maxAge: 7 * 24 * 60 * 60 * 1000, // 设置缓存时间，这里是7天
    setHeaders(res, path) {
      if (
        path.endsWith(".jpg") ||
        path.endsWith(".png") ||
        path.endsWith(".gif")
      ) {
        res.setHeader("Cache-Control", ["public", `max-age=${this.maxAge}`]);
      }
    },
  }),
);
const port = process.env.PORT || 6776;
app.listen(port, () => {
  console.log(`Server running on port http://localhost:${port}`);
});
